#!/usr/bin/env python3
"""
调试拓扑排序算法
"""

def debug_topological_sort(dependencies):
    """
    调试版本的拓扑排序算法
    """
    print(f"输入依赖图: {dependencies}")
    
    # 构建完整的依赖图，确保所有被依赖的节点都包含在内
    complete_graph = {}
    # 首先添加所有直接定义的节点
    for node in dependencies:
        complete_graph[node] = list(dependencies[node])
    
    # 然后添加所有被依赖但未在顶层定义的节点
    for node in dependencies:
        for dep in dependencies[node]:
            if dep not in complete_graph:
                complete_graph[dep] = []
    
    print(f"完整依赖图: {complete_graph}")
    
    # 构建入度表
    in_degree = {}
    # 初始化所有节点的入度
    for node in complete_graph:
        if node not in in_degree:
            in_degree[node] = 0
        for dep in complete_graph[node]:
            if dep not in in_degree:
                in_degree[dep] = 0
            in_degree[dep] += 1
    
    print(f"入度表: {in_degree}")
    
    # 找到所有入度为0的节点
    queue = [node for node in in_degree if in_degree[node] == 0]
    print(f"初始队列: {queue}")
    
    result = []
    
    while queue:
        node = queue.pop(0)
        result.append(node)
        print(f"处理节点: {node}, 当前结果: {result}")
        
        # 更新依赖该节点的所有节点的入度
        for dependent in [n for n in complete_graph if node in complete_graph[n]]:
            in_degree[dependent] -= 1
            print(f"  更新 {dependent} 的入度为 {in_degree[dependent]}")
            if in_degree[dependent] == 0:
                queue.append(dependent)
                print(f"  将 {dependent} 加入队列")
    
    print(f"最终结果: {result}")
    print(f"入度表最终状态: {in_degree}")
    
    # 检查是否有循环依赖
    if len(result) != len(in_degree):
        print("检测到循环依赖!")
        return None
    else:
        print("没有循环依赖")
        return result

# 测试用例
print("测试用例1: 正常的依赖图")
dependency_graph1 = {
    "demo_plugin": ["logging_plugin"],
    "logging_plugin": []
}

result1 = debug_topological_sort(dependency_graph1)
print(f"结果: {result1}\n")

print("测试用例2: 循环依赖图")
dependency_graph2 = {
    "plugin_a": ["plugin_b"],
    "plugin_b": ["plugin_c"],
    "plugin_c": ["plugin_a"]
}

result2 = debug_topological_sort(dependency_graph2)
print(f"结果: {result2}\n")